package com.csw.controller;

import com.csw.entity.Dir;
import com.csw.entity.File;
import com.csw.entity.Friend;
import com.csw.entity.Share;
import com.csw.entity.User;
import com.csw.service.DirService;
import com.csw.service.FileService;
import com.csw.service.FriendService;
import com.csw.service.ShareService;
import com.csw.service.UserService;
import com.csw.util.ObjectIdUtil;
import com.csw.util.TextCopyFileAndMove;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RequestMapping("friend")
@RestController
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShareService shareService;
    @Autowired
    private FileService fileService;
    @Autowired
    private DirService dirService;

    /**
     * @param session
     * @return
     */
    @RequestMapping("friQue")
    public String friQue(HttpSession session) {

            User user = (User) session.getAttribute("user");
            if (user == null) {
                return "redirect:/user/logOut";
            }
            List<Friend> friendList = friendService.selectByUid(user.getId());


            List<Share> shareListfile = shareService.queryAllFile(user.getId());
            for (Share share : shareListfile) {
                if (share.getFile() == null) {
                    shareService.deleteById(share.getId());
                }
            }
            shareListfile = shareService.queryAllFile(user.getId());

            List<Share> shareListDir = shareService.queryAllDir(user.getId());
            for (Share share : shareListDir) {
                if (share.getDir() == null) {
                    shareService.deleteById(share.getId());
                }
            }
            shareListDir = shareService.queryAllDir(user.getId());
            session.setAttribute("friendList", friendList);
            session.setAttribute("shareListfile", shareListfile);
            session.setAttribute("shareListDir", shareListDir);
            return "redirect:/jsp/front/main/detail/friend.jsp";

    }

    /**
     * @param session
     * @param inSearchName
     * @param aa
     * @return
     */
    @RequestMapping("serFri")
    public String serFri(HttpSession session, String inSearchName, String aa) {

        if (aa == null) {
                if (!"".equals(inSearchName)) {
                    session.setAttribute("serFri", inSearchName);
                } else {
                    session.setAttribute("message", "输入为空，请检查后重新输入");
                    session.setAttribute("serFri", null);
                }
                return "redirect:/friend/friQue";
            } else if (aa.equals("0")) {
                session.setAttribute("message", "你已经取消操作");
                session.setAttribute("serFri", null);
                return "redirect:/friend/friQue";
            } else if (aa.equals("1")) {
                String fuid = (String) session.getAttribute("serFri");
                User user = (User) session.getAttribute("user");
                User fuser = userService.selectUserById(fuid);
                if (fuser == null) {
                    session.setAttribute("message", "你说查找的用户不存在");
                    session.setAttribute("serFri", null);
                    return "redirect:/friend/friQue";
                } else {
                    //判断好友里有没有这个好友
                    Friend friend = friendService.queryByUidFid(user.getId(), fuid);
                    if (friend != null) {
                        session.setAttribute("message", "已经有这个好友");
                        session.setAttribute("serFri", null);
                        return "redirect:/friend/friQue";
                    } else {
                        Friend friend1 = new Friend();
                        friend1.setId(ObjectIdUtil.getObjectId());
                        friend1.setUser(user);
                        friend1.setFuser(fuser);
                        friendService.insertFriend(friend1);
                        //反向添加好友
                        Friend friend2 = new Friend();
                        friend2.setId(ObjectIdUtil.getObjectId());
                        friend2.setUser(fuser);
                        friend2.setFuser(user);
                        friendService.insertFriend(friend2);
                        session.setAttribute("message", "添加好友成功");
                        session.setAttribute("serFri", null);
                        return "redirect:/friend/friQue";
                    }
                }
            }
            return "redirect:/friend/friQue";

    }

    /**
     * @param session
     * @param fid
     * @return
     */
    @RequestMapping("celFriend")
    public String celFriend(HttpSession session, String fid) {

        Friend friend = friendService.selectById(fid);
            friendService.deleteById(fid);
            Friend friend1 = friendService.selectUidFid(friend.getFuser().getId(), friend.getUser().getId());
            friendService.deleteById(friend1.getId());
            session.setAttribute("message", "删除好友成功");
            return "redirect:/friend/friQue";

    }

    /**
     * @param session
     * @return
     */
    @RequestMapping("getMessage")
    public String getMessage(HttpSession session) {

        String message = (String) session.getAttribute("message");
            return message;

    }

    /**
     * @param session
     * @return
     */
    @RequestMapping("cleMessage")
    public String cleMessage(HttpSession session) {

        session.setAttribute("message", null);
            return "redirect:/friend/friQue";

    }

    @RequestMapping("sharefile")
    public String share(String sharefileId, HttpSession session, String uid, String aa) {

        User user = (User) session.getAttribute("user");
            if (sharefileId != null) {
                List<Friend> friendList = friendService.selectByUid(user.getId());
                session.setAttribute("friendList", friendList);
                session.setAttribute("sharefile", sharefileId);
                return "redirect:/mydoc/queryOne";
            } else {
                if (aa != null) {
                    session.setAttribute("friendList", null);
                    session.setAttribute("sharefile", null);
                    session.setAttribute("message", "你已经取消分享");
                    return "redirect:/mydoc/queryOne";
                } else {
                    sharefileId = (String) session.getAttribute("sharefile");
                    File file = fileService.selectFileById(sharefileId);
                    Share share = new Share();
                    share.setId(ObjectIdUtil.getObjectId());
                    share.setFromId(user.getId());
                    share.setToId(uid);
                    share.setFile(file);
                    shareService.insert(share);
                    //分享成功
                    file.setOptionTime(new Date());
                    fileService.updateTime(file);
                    session.setAttribute("friendList", null);
                    session.setAttribute("sharefile", null);
                    session.setAttribute("message", "分享成功");
                    return "redirect:/mydoc/queryOne";
                }
            }

    }

    @RequestMapping("onsave")
    public String onsave(String fid, HttpSession session, String aa) throws Exception {

            User user = (User) session.getAttribute("user");
            if (fid != null) {
                session.setAttribute("onsave", fid);
                session.setAttribute("message", "去选择保存路径");
                return "redirect:/mydoc/queryOne";
            } else {
                if (aa.equals("0")) {
                    session.setAttribute("onsave", null);
                    return "redirect:/mydoc/queryOne";
                } else if (aa.equals("1")) {
                    fid = (String) session.getAttribute("onsave");
                    Share share = shareService.queryById(fid);
                    File file = fileService.selectFileById(share.getFile().getId());
                    String folderid = (String) session.getAttribute("did");
                    Dir dir = dirService.selectById(folderid);
                    //保存文件
                    //服务器移动
                    String topath = dir.getPath() + "\\" + dir.getName();
                    java.io.File file1 = new java.io.File(file.getPath() + "\\" + file.getNewName());
                    String name = file.getNewName();
                    TextCopyFileAndMove.copyFileToDir(topath, file1, name);
                    //服务器移动完成

                    //进入处理数据库环节
                    //更新数据
                    file.setId(ObjectIdUtil.getObjectId());
                    file.setPath(topath);
                    file.setDir(dir);
                    file.setUser(user);
                    //md5
                    List<File> filem = fileService.selectFileByPidAndMd5(dir.getId(), file.getCheckMd5());
                    if (filem.size() != 0) {
                        //已有相同文件，不在进行操作
                    } else {
                        //当前文件夹下没有相同的文件
                        fileService.addFile(file);
                        session.setAttribute("fileYdid", null);
                    }
                    //保存成功
                    session.setAttribute("onsave", null);
                    session.setAttribute("message", "保存成功");
                    return "redirect:/mydoc/queryOne";
                }
            }

            return "redirect:/mydoc/queryOne";

    }

    @RequestMapping("onsaveDir")
    public String onsaveDir(String fid, HttpSession session, String aa) throws Exception {

            User user = (User) session.getAttribute("user");
            if (fid != null) {
                session.setAttribute("onsaveDir", fid);
                session.setAttribute("message", "去选择保存路径");
                return "redirect:/mydoc/queryOne";
            } else {
                if (aa.equals("0")) {
                    session.setAttribute("onsaveDir", null);
                    return "redirect:/mydoc/queryOne";
                } else if (aa.equals("1")) {
                    fid = (String) session.getAttribute("onsaveDir");
                    Share share = shareService.queryById2(fid);
                    User userold = userService.selectUserById(share.getFromId());
                    //要移动的文件夹
                    Dir dir1 = dirService.selectById(share.getDir().getId());
                    String folderid = (String) session.getAttribute("did");
                    //目标文件夹
                    Dir dir = dirService.selectById(folderid);
                    //保存文件


                    if (dir.getId().equals(dir1.getDid())) {
                        //有相同目录不移动
                        session.setAttribute("message", "已经复制过了");
                        session.setAttribute("onsaveDir", null);
                        return "redirect:/mydoc/queryOne";
                    }
                    int status = 1;
                    String patha = dir.getPath() + "\\" + dir.getName();
                    Dir dirSearch = dirService.selectByNamePid(user, status, patha, dir1.getName());
                    if (dirSearch != null) {
                        //同一目录不移动
                        session.setAttribute("message", "已经复制过了");
                        session.setAttribute("onsaveDir", null);
                        return "redirect:/mydoc/queryOne";
                    }
                    String path = dir.getPath() + "\\" + dir.getName();
                    String path1 = dir1.getPath() + "\\" + dir1.getName();
                    String path0 = path1.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");

                    //要保证这两个方法都能查到pid,uid
                    //2.查询所有

                    List<File> fileList = fileService.selectAllFileByFatherFolder(path0, userold, status);

                    List<Dir> dirList = dirService.selectAllFolderBy(path0, userold, status);

                    dir1.setDid(dir.getId());
                    dirList.add(dir1);
                    String dir0Id = dir1.getId() + "1";
                    String dir0Pid = dir1.getDid();

                    //数据库操作
                    //5.数据库复制信息
                    String pathFirst;

                    for (File file : fileList) {
                        pathFirst = dir.getPath() + "\\" + dir.getName();
                        String[] ff = file.getPath().split("\\\\");

                        boolean judge = false;
                        for (int i = 0; i < ff.length; i++) {
                            //要移动文件夹的名字等于文件路径上的名字
                            if (ff[i].equals(dir1.getName())) {
                                //进入到judge判断
                                judge = true;
                            }
                            if (judge) {
                                pathFirst += "\\" + ff[i];
                            }
                        }
                        //

                        //处理完成，
                        //进入处理数据库环节
                        //更新数据
                        file.setId(file.getId() + "1");
                        file.setUser(user);
                        file.setPath(pathFirst);
                        fileService.addFile(file);
                        //一起添加的话，他的pid就找不到了
                        String filePid = file.getDir().getId() + "1";
                        String fileId = file.getId();
                        fileService.updateDid(fileId, filePid);
                    }

                    for (Dir dir2 : dirList) {
                        pathFirst = dir.getPath() + "\\" + dir.getName();
                        String[] ff = dir2.getPath().split("\\\\");
                        boolean judge = false;
                        for (int i = 0; i < ff.length; i++) {
                            if (ff[i].equals(dir1.getName())) {
                                judge = true;
                            }
                            if (judge) {
                                pathFirst += "\\" + ff[i];
                            }
                        }
                        //处理完成，
                        //进入处理数据库环节
                        //更新数据
                        dir2.setPath(pathFirst);
                        dir2.setId(dir2.getId() + "1");
                        dir2.setUser(user);
                        dir2.setDid(dir2.getDid() + "1");

                        dirService.addRootDir(dir2);

                    }
                    //最后还原一下原来要移动文件的pid
                    dirService.updatePid(dir0Id, dir0Pid);
                    //1.服务器移动
                    TextCopyFileAndMove.copyDir(path, path1);
                    //服务器移动完成

                    //保存成功
                    session.setAttribute("onsaveDir", null);
                    session.setAttribute("message", "保存成功");
                    return "redirect:/mydoc/queryOne";
                }
            }
            return "redirect:/mydoc/queryOne";

    }

    @RequestMapping("shareDir")
    public String shareDir(String ShareDirId, HttpSession session, String uid, String aa) {

        User user = (User) session.getAttribute("user");
            if (ShareDirId != null) {
                //文件sharefileId不为空
                List<Friend> friendList = friendService.selectByUid(user.getId());
                session.setAttribute("friendList", friendList);
                session.setAttribute("shareDir", ShareDirId);
                return "redirect:/mydoc/queryOne";
            } else {
                if (aa != null) {
                    session.setAttribute("friendList", null);
                    session.setAttribute("shareDir", null);
                    session.setAttribute("message", "你已经取消分享");
                    return "redirect:/mydoc/queryOne";
                } else {
                    //文件sharefileId空
                    ShareDirId = (String) session.getAttribute("shareDir");
                    Dir dir = dirService.selectById(ShareDirId);
                    Share share = new Share();
                    share.setId(ObjectIdUtil.getObjectId());
                    share.setFromId(user.getId());
                    share.setToId(uid);
                    share.setDir(dir);
                    shareService.insert(share);
                    //分享成功
                    session.setAttribute("friendList", null);
                    session.setAttribute("shareDir", null);
                    session.setAttribute("message", "分享成功");
                    return "redirect:/mydoc/queryOne";
                }
            }

    }
}
